#include <stdio.h>
#include <math.h>

#include "mq2.h"
#include "iot_adc.h"
#include "iot_errno.h"

/**
 *  ppm：为可燃气体的浓度
 *  VRL：电压输出值
 *  Rs：器件在不同气体，不同浓度下的电阻值
 *  R0：器件在洁净空气中的电阻值
 *  RL：负载电阻阻值
 */
uint32_t MQ2_GetData(double *ppm)
{
    uint32_t ret;
    uint16_t data = 0;
    float voltage;
    float Rs;
    //  ADC_Channal_5(GPIO11)  自动识别模式  CNcomment:4次平均算法模式 CNend
    ret = AdcRead(IOT_ADC_CHANNEL_5, &data, IOT_ADC_EQU_MODEL_4, IOT_ADC_CUR_BAIS_DEFAULT, 0xFF);

    if (ret != IOT_SUCCESS)
    {
        printf("AdcRead fail, ret=%d\r\n", ret);
        return ret;
    }
    // Rs/R0 = 11.5428*ppm^(-0.6549)
    voltage = (float)(data * 1.8 * 4 / 4096.0); // data * 1.8 * 4 / 4096.0 将码字转换为电压
    Rs = (5 - voltage) / voltage;
    *ppm = 10 * pow(11.5428 * 19 / Rs, 1.0 / 0.6549);
    // printf("\r\n data=%d, voltage=%f, Rs=%f, ppm=%.2lf\r\n", data, voltage, Rs, *ppm);
    return IOT_SUCCESS;
}

// 光照传感器
uint32_t RES_GetData(float *lum)
{
    uint32_t ret;
    uint16_t data = 0;
    // ADC_Channal_3(GPIO7)  自动识别模式  CNcomment:4次平均算法模式 CNend
    ret = AdcRead(IOT_ADC_CHANNEL_3, &data, IOT_ADC_EQU_MODEL_4, IOT_ADC_CUR_BAIS_DEFAULT, 0xFF);

    if (ret != IOT_SUCCESS)
    {
        printf("AdcRead fail, ret=%d\r\n", ret);
        return IOT_FAILURE;
    }
    *lum = (float)(data * 1.8 * 4 / 4096.0); // data * 1.8 * 4 / 4096.0 将码字转换为电压

    // printf("\r\n data=%d, lum=%f\r\n", data, *lum);
    return IOT_SUCCESS;
}
